import { Py } from './const'
import { get } from 'lodash-es'

export function parseApiOptions(opts: any, params: any) {
    opts = { ...opts }
    parseURL(opts, params)
    parseApiParams(opts, params)
    return opts
}

export function parseApiParams(opts: any, params: any) {
    if ([Py.PARTIAL_QUERY, Py.REQUIRED_QUERY].includes(opts.paramTy)) {
        opts.params = params ?? {}
    } else if (![HttpMethod.GET, HttpMethod.HEAD].includes(opts.method)) {
        opts.body = params ?? {}
    }
    return opts
}

export function parseURL(opts: any, params: any = {}) {
    let url: string = opts.url
    const matches = url.matchAll(/:([\w.]+)/g)
    if (matches === null) return opts
    params = toValue(params)
    Array.from(matches).forEach((match) => {
        url = url.replace(match[0], get(params, match[1]))
    })
    opts.url = url
    return opts
}
